importScripts("./osgblodrange.js");
importScripts("./osgbtexturedata.js");
importScripts("./osgbmeshdata.js");
importScripts("./osgbparser.js");
importScripts("./pako.min.js");

function OSGBProcessor() {
    this.parser = new OSGBParser();
}

Object.assign(OSGBProcessor.prototype, {

	process: function (message) {
        if (message.fun == "processMesh") {
            this.loadMesh(message);
        }
	},

    loadMesh: function (message) {
        var _this = this;
        var url = this.getRequestURL(message.url, message.key);
        var xhr = new XMLHttpRequest();
        xhr.timeout = 0;
        xhr.withCredentials = false;
        xhr.responseType = "arraybuffer";
        xhr.onload = function() {
            var response = null;
            if (this.status === 200) {
                //response = this.response;
                response = pako.inflate(this.response).buffer;
            }
            _this.processMesh(message, response);
        }
        xhr.open("GET", url, true);
        //xhr.setRequestHeader("Accept-Encoding", "gzip,deflate");
        xhr.send(null);
    },

    processMesh: function (message, response) {
	    var loaded = false;
	    if (response != null) {
            loaded = this.parser.parser(response);
        }
        var transferableObjects = [];
	    if (loaded) {
            message.layouts = this.parser.toTransferableObjects(transferableObjects);
        }
        postMessage({result: message, buffer: transferableObjects}, transferableObjects);
    },

    getRequestURL: function (url, key) {
        url = url.replace(/{key}/, key);
        return url;
    },

} );

